package com.chinameyer.equipment_ebook.controller;

import com.alibaba.fastjson.JSONArray;
import com.chinameyer.equipment_ebook.bo.MyDefineBO;
import com.chinameyer.equipment_ebook.common.result.ApiResponse;
import com.chinameyer.equipment_ebook.common.result.ApiResponseWithPaging;
import com.chinameyer.equipment_ebook.dto.UploadMsgDTO;
import com.chinameyer.equipment_ebook.service.EventService;
import com.chinameyer.equipment_ebook.vo.DocumentsVVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author meyer@HongYe
 */
@RestController
@RequestMapping("/v1/event/")
@Validated
@CrossOrigin
public class EventController {

    @Autowired
    private EventService eventService;
    @Autowired
    private MyDefineBO myDefineBO;


    /**
     * 上传 PDF 文档
     * @param file PDF文档
     * @return 上传结果响应
     */
    @PostMapping("uploadPDF")
    public ApiResponse uploadPDF(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return new ApiResponse(400,"上传失败，请选择文件",0);
        }
        String fileName = file.getOriginalFilename();
        String path = myDefineBO.getPdfPath();
        File dest = new File(path + fileName);
        if (!dest.exists()){
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);
            String url = myDefineBO.getDomain() + "/uploads/" + fileName;
            return new ApiResponse(200,"success",url);
        } catch (IOException e) {
            return new ApiResponse(400,"上传失败",0);
        }
    }


    /**
     * 新增PDF文档
     * @param equipmentNo       设备编码
     * @param uploadMsgDTOList  说明书上传数据数组
     * @param userId            上传人ID
     * @return 新增结果响应
     */
    @PostMapping("addDocument")
    public ApiResponse addDocument(@RequestParam(name = "equipmentNo") String equipmentNo,
                                   @RequestParam(name = "uploadMsgDTOList") String uploadMsgDTOList,
                                   @RequestParam(name = "userId") Integer userId){
        List<UploadMsgDTO> uploadMsgDTOArrayList = JSONArray.parseArray(uploadMsgDTOList, UploadMsgDTO.class);//转换成JSONArray 格式
        String isExist = this.eventService.checkManualIsExist(equipmentNo,uploadMsgDTOArrayList);
        if(!StringUtils.isEmpty(isExist)){
            return new ApiResponse(400,isExist,0);
        }
        boolean isAddSuccess = this.eventService.addDocument(equipmentNo,uploadMsgDTOArrayList,userId);
        if(!isAddSuccess){
            return new ApiResponse(400,"添加失败，请重新添加！",0);
        }
        return new ApiResponse(200,"success",1);
    }


    /**
     * 更新PDF文档
     * @param id  eventId
     * @param url PDF文档url
     * @return 更新结果响应
     */
    @PostMapping("updateDocument")
    public ApiResponse updateDocument(@RequestParam(name = "id") Integer id,
                                      @RequestParam(name = "url") String url){
        boolean isUpdateSuccess = this.eventService.updateDocument(id,url);
        if(!isUpdateSuccess){
            return new ApiResponse(400,"更新失败，请重新操作！",0);
        }
        return new ApiResponse(200,"success",1);
    }


    /**
     * 获取PDF文档
     * @param equipmentNo 设备编码
     * @param manualType  说明书类型
     * @param count       当前页数目
     * @param page        当前分页
     * @return 查看结果响应
     */
    @GetMapping("getDocuments")
    public ApiResponseWithPaging getDocuments(@RequestParam(name = "equipmentNo",required = false,defaultValue = "") String equipmentNo,
                                              @RequestParam(name = "manualType",required = false,defaultValue = "") String manualType,
                                              @RequestParam(name = "userId") Integer userId,
                                              @RequestParam(name = "count", required = false, defaultValue = "10")
                                              @Min(value = 1, message = "分页数量必须为正整数") Integer count,
                                              @RequestParam(name = "page", required = false, defaultValue = "1")
                                              @Min(value = 0, message = "分页必须为正整数") Integer page){
        List<DocumentsVVO> documentsVOS = this.eventService.getAllDocuments(equipmentNo,manualType,userId,count,page - 1);
        int total = this.eventService.getTotalDocuments(equipmentNo,manualType,userId);
        return new ApiResponseWithPaging(200,"success",documentsVOS,total);
    }
}
